package cj.web.kly.controllers;

import java.io.File;
import java.text.ParseException;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.web.admin.constants.Constants;
import cj.web.admin.utils.DateUtils;
import cj.web.admin.utils.ReadConfigProperties;
import cj.web.admin.utils.ReturnUUID;
import cj.web.kly.constants.GroupPeopleTypeEnum;
import cj.web.kly.domain.GroupDep;
import cj.web.kly.domain.GroupInfor;
import cj.web.kly.domain.GroupPeople;
import cj.web.kly.domain.SpecialistLabel;
import cj.web.kly.service.GroupDepService;
import cj.web.kly.service.GroupInforService;
import cj.web.kly.service.GroupPeopleService;
import cj.web.kly.service.SpecialistLabelService;
import cj.web.login.controllers.BaseController;

@Path("/groupPeople")
public class GroupPeopleController extends BaseController{

	private static Logger logger = Logger.getLogger(GroupPeopleController.class.getName());
	
	@Autowired
	private GroupPeopleService groupPeopleService;
	
	@Autowired
	private GroupDepService groupDepService;
	
	@Autowired
	private GroupInforService groupInforService;
	
	@Autowired
	private SpecialistLabelService specialistLabelService;
	
	@Get("show")
	public String show(Model model,GroupPeople groupPeople) {
		return "/views/kly/groupPeopleList.vm";
	}
	
	@Post("getList")
	public String queryList(GroupPeople groupPeople) {
	
		//当前页  
		groupPeople.setStart((groupPeople.getPage()-1)*groupPeople.getRows());
		groupPeople.setLength(groupPeople.getRows());
		
		JSONObject jo = new JSONObject();
		
		Map rep = groupPeopleService.query(groupPeople);
		
		List<GroupPeople> objs = (List<GroupPeople>) rep.get("groupPeoplelis");
		for(GroupPeople obj:objs){
			if(null == obj.getLabelId()){
				obj.setLabelName("");
			}else{
				SpecialistLabel specialistLabel= specialistLabelService.queryById(obj.getLabelId());
				obj.setLabelName(specialistLabel.getName());
			}
			
			obj.setTypeName(GroupPeopleTypeEnum.getName(obj.getType()));
		}
		
		int size = (int) rep.get("size");
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model,@Param("depId") int depId){
		GroupDep groupDep = groupDepService.queryById(depId);
		GroupInfor groupInfor = groupInforService.queryById(groupDep.getGroupId());
		model.add("groupPeopleTypeEnum",EnumSet.allOf(GroupPeopleTypeEnum.class));
		model.add("depId", depId);
		model.add("depName", groupDep.getName());
		model.add("groupId", groupInfor.getId());
		model.add("groupName", groupInfor.getName());
		return "/views/kly/groupPeopleDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,GroupPeople groupPeople,HttpServletRequest request,@Param("uploadimage") MultipartFile file)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		if(null == groupPeople.getTreeIdIn() || "".equals(groupPeople.getTreeIdIn())){
			groupPeople.setLabelId(null);
		}else{
			groupPeople.setLabelId(Integer.parseInt(groupPeople.getTreeIdIn()));
		}
		
		groupPeople.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
		groupPeople.setCreateAt(DateUtils.getNowTime());
		groupPeople.setCreateUser(returnSessionObj(request).getAccount());
		groupPeople.setUpdateAt(DateUtils.getNowTime());
		groupPeople.setUpdateUser(returnSessionObj(request).getAccount());
		
		try{
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                groupPeople.setPhoto(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
			groupPeopleService.create(groupPeople);
		}
		catch(Exception e){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id) throws ParseException
	{
		model.add("groupPeopleTypeEnum",EnumSet.allOf(GroupPeopleTypeEnum.class));
		GroupPeople groupPeople = groupPeopleService.queryById(id);
		
		if(null == groupPeople.getLabelId() || "".equals(groupPeople.getLabelId())){
			groupPeople.setLabelName("");
		}else{
			SpecialistLabel specialistLabel= specialistLabelService.queryById(groupPeople.getLabelId());
			groupPeople.setLabelName(specialistLabel.getName());
		}
		
		groupPeople.setBirthdate(DateUtils.formatDateStr(groupPeople.getBirthdate(), DateUtils.DATE_SMALL_STR));
		
		model.add("groupPeople", groupPeople);
		return "/views/kly/groupPeopleEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,GroupPeople groupPeople,HttpServletRequest request,@Param("uploadimage") MultipartFile file)
	{
		JSONObject jo = new JSONObject();
		
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if(null == groupPeople.getTreeIdIn() || "".equals(groupPeople.getTreeIdIn())){
			groupPeople.setLabelId(null);
		}else{
			groupPeople.setLabelId(Integer.parseInt(groupPeople.getTreeIdIn()));
		}
		
		groupPeople.setUpdateAt(DateUtils.getNowTime());
		groupPeople.setUpdateUser(returnSessionObj(request).getAccount());
		
		try {
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                groupPeople.setPhoto(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
			groupPeopleService.update(groupPeople);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("Ids") String Ids)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			groupPeopleService.deleteById(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
	
	
	//-----------------------groupDep
	@Post("getGroupDepList")
	public String queryGroupDepList(@Param("groupId")int groupId) {
		JSONObject jo = new JSONObject();
		List<GroupDep> objs = groupDepService.queryByGroupId(groupId);
		jo.put("rows", objs);
		return "@"+jo.toString();
	}
	
	@Get("createGroupDepPage")
	public String createGroupDepPage(Model model,@Param("groupId")int groupId){
		model.add("groupId", groupId);
		return "/views/kly/groupDepDetail.vm";
	}
	
	@Post("createGroupDep")
	public String createGroupDep(Model model,GroupDep groupDep,HttpServletRequest request,@Param("uploadimage") MultipartFile file){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		groupDep.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
		groupDep.setCreateUser(returnSessionObj(request).getAccount());
		groupDep.setUpdateUser(returnSessionObj(request).getAccount());
		
		try{
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                groupDep.setCarouselImage(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
			groupDepService.create(groupDep);
		}catch(Exception e){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("editGroupDep")
	public String editGroupDep(Model model,@Param("id") int id){
		GroupDep obj = groupDepService.queryById(id);
		model.add("groupDep", obj);
		return "/views/kly/groupDepEdit.vm";
	}
	
	@Post("updateGroupDep")
	public String updateGroupDep(Model model,GroupDep groupDep,HttpServletRequest request,@Param("uploadimage") MultipartFile file){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		groupDep.setUpdateUser(returnSessionObj(request).getAccount());
		
		try {
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                groupDep.setCarouselImage(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
			groupDepService.update(groupDep);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteGroupDepById")
	public String deleteGroupDepById(Model model,@Param("Ids") String Ids)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		for(String id :Ids.split(",")){
			groupDepService.deleteById(Integer.parseInt(id));
		}
		
		return "@"+jo.toString();
	}
	
	//----------------------noExistGroupPeople
	@Get("noExistPeople")
	public String noExistPeople(Model model,GroupPeople groupPeople) {
		return "/views/kly/noExistPeopleList.vm";
	}
	
	@Post("getNoExistList")
	public String queryNoExistList(GroupPeople groupPeople) {
	
		//当前页  
		groupPeople.setStart((groupPeople.getPage()-1)*groupPeople.getRows());
		groupPeople.setLength(groupPeople.getRows());
		
		JSONObject jo = new JSONObject();
		
		Map rep = groupPeopleService.queryNoExist(groupPeople);
		
		List<GroupPeople> objs = (List<GroupPeople>) rep.get("groupPeoplelis");
		for(GroupPeople obj:objs){
			if(null == obj.getLabelId()){
				obj.setLabelName("");
			}else{
				SpecialistLabel specialistLabel= specialistLabelService.queryById(obj.getLabelId());
				obj.setLabelName(specialistLabel.getName());
			}
			obj.setTypeName(GroupPeopleTypeEnum.getName(obj.getType()));
		}
		
		int size = (int) rep.get("size");
		jo.put("rows", objs);
		jo.put("total", size);
		return "@"+jo.toString();
	}
	
	@Get("createNoExistPage")
	public String createNoExistPage(Model model,@Param("depId") int depId){
		model.add("groupPeopleTypeEnum",EnumSet.allOf(GroupPeopleTypeEnum.class));
		return "/views/kly/noExistPeopleDetail.vm";
	}
	
	@Post("createNoExist")
	public String createNoExist(Model model,GroupPeople groupPeople,HttpServletRequest request,@Param("uploadimage") MultipartFile file)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		groupPeople.setType(1);
		groupPeople.setGroupId(null);
		groupPeople.setDepId(null);
		
		if(null == groupPeople.getTreeIdIn() || "".equals(groupPeople.getTreeIdIn())){
			groupPeople.setLabelId(null);
		}else{
			groupPeople.setLabelId(Integer.parseInt(groupPeople.getTreeIdIn()));
		}
		
		groupPeople.setDeleteFlag(Constants.deleteFlag.deleteFlag_1);
		groupPeople.setCreateAt(DateUtils.getNowTime());
		groupPeople.setCreateUser(returnSessionObj(request).getAccount());
		groupPeople.setUpdateAt(DateUtils.getNowTime());
		groupPeople.setUpdateUser(returnSessionObj(request).getAccount());
		
		try{
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                groupPeople.setPhoto(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
			groupPeopleService.create(groupPeople);
		}
		catch(Exception e){
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("editNoExist")
	public String editNoExist(Model model,@Param("id") int id) throws ParseException
	{
		model.add("groupPeopleTypeEnum",EnumSet.allOf(GroupPeopleTypeEnum.class));
		GroupPeople groupPeople = groupPeopleService.queryNoExistById(id);
		
		if(null == groupPeople.getLabelId() || "".equals(groupPeople.getLabelId())){
			groupPeople.setLabelName("");
		}else{
			SpecialistLabel specialistLabel= specialistLabelService.queryById(groupPeople.getLabelId());
			groupPeople.setLabelName(specialistLabel.getName());
		}
		
		groupPeople.setBirthdate(DateUtils.formatDateStr(groupPeople.getBirthdate(), DateUtils.DATE_SMALL_STR));
		
		model.add("groupPeople", groupPeople);
		return "/views/kly/noExistPeopleEdit.vm";
	}
	
	@Post("updateNoExist")
	public String updateNoExist(Model model,GroupPeople groupPeople,HttpServletRequest request,@Param("uploadimage") MultipartFile file)
	{
		JSONObject jo = new JSONObject();
		
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		groupPeople.setType(1);
		groupPeople.setGroupId(null);
		groupPeople.setDepId(null);
//		groupPeople.setLabelId(Integer.parseInt(groupPeople.getTreeIdIn()));
		
		if(null == groupPeople.getTreeIdIn() || "".equals(groupPeople.getTreeIdIn())){
			groupPeople.setLabelId(null);
		}else{
			groupPeople.setLabelId(Integer.parseInt(groupPeople.getTreeIdIn()));
		}
		
		groupPeople.setUpdateAt(DateUtils.getNowTime());
		groupPeople.setUpdateUser(returnSessionObj(request).getAccount());
		
		try {
			
			// 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	            	String path = ReadConfigProperties.getValue("uploadFilePath");
	            	//判断文件是否存在，不存在创建文件
	            	Map rep = ReturnUUID.getFolder(path);
	            	path = rep.get("allpath").toString();//所在的全路径
	            	//文件名
	                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
	                // 转存文件  
	                file.transferTo(new File(path+"/"+fileName));  
	                jo.put("filePath", rep.get("filepath")+"/"+fileName);
	                
	                groupPeople.setPhoto(rep.get("filepath")+"/"+fileName);//文件路径
	            } catch (Exception e) {  
	                e.printStackTrace();  
	                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
	            }  
	        } 
			
			groupPeopleService.update(groupPeople);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
}